package com.axend.vetwavve.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.android.jws.JwsManager
import com.axend.lib_base.base.activity.BaseVVDActivity
import com.axend.lib_base.bean.RadarUpBean
import com.axend.lib_base.help.otgserial.SerialInter
import com.axend.lib_base.help.otgserial.SerialManage
import com.axend.lib_base.utils.ScreenAutoAdapter
import com.axend.lib_base.utils.UsbUtils
import com.axend.lib_service.ARouterPath
import com.axend.vetwavve.databinding.ActivityUsbDeviceConnectBinding
import com.axend.vetwavve.viewmodel.UsbDeviceConnectViewModel
import com.guide.zx03c.GuideInterface
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

/**
 * @description设备连接页面
 * @author admins
 * @time 2024/6/6 17:48
 */
@Route(path = ARouterPath.ACTIVITY_USB_DEVICE_CONNECT)
class UsbDeviceConnectActivity :
    BaseVVDActivity<UsbDeviceConnectViewModel, ActivityUsbDeviceConnectBinding>(), SerialInter {

    /*红外设备VID*/
    private val INFRARED_VENDOR_ID = 1317
    private val INFRARED_PRODUCT_ID = 42144

    /*radar*/
    private val RADAR_VENDOR_ID = 6790
    private val RADAR_PRODUCT_ID = 21971
    override fun onCreate(savedInstanceState: Bundle?) {
        /*处理横竖屏问题*/
        val configuration: Configuration = resources.configuration
        if (configuration.orientation === Configuration.ORIENTATION_LANDSCAPE) {
            ScreenAutoAdapter.match(this, 1920f)
        } else if (configuration.orientation === Configuration.ORIENTATION_PORTRAIT) {
            ScreenAutoAdapter.match(this, 1200f)
        }
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        super.onCreate(savedInstanceState)
    }

    override fun init(savedInstanceState: Bundle?) {
        XXPermissions.with(this).permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.CAMERA)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .request { permissions, allGranted ->

            }

        val filter = IntentFilter()
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)

        registerReceiver(usbBroadcastReceiver, filter)

        initInfrared()


    }

    private fun initInfrared() {
        UsbUtils.init(this)

//        if (UsbUtils.isDeviceConnected(INFRARED_VENDOR_ID,INFRARED_PRODUCT_ID)
//        ){
//            /*跳转*/
//            Intent(this@UsbDeviceConnectActivity, MainActivity::class.java).apply {
//                flags=Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
//                startActivity(this)
//            }
//            finish()
//        }
        SerialManage.getInstance().init(this, true)
        SerialManage.getInstance().open(true)
        val port = 1
        val jwsManager = JwsManager.create(this)
        jwsManager.jwsSetExtrnalGpioValue(port, true)
//        if (SerialManage.getInstance().open(false)) {
//            /*跳转*/
//            Intent(this@UsbDeviceConnectActivity, MainActivity::class.java).apply {
//                flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
//                startActivity(this)
//            }
//            finish()
//        }

    }

    fun onClick(view: android.view.View) {
//        ARouter.getInstance().build(ARouterPath.ACTIVITY_MAIN).navigation(this)
//        Intent(this@UsbDeviceConnectActivity, MainActivity::class.java).apply {
//            startActivity(this)
//        }
//        finish()
    }

    /**
     * Usb广播监听
     */
    private val usbBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                // USB设备插入
                UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                    val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                    // 处理设备插入的逻辑
                    mBinding.tvDeviceTips.text =
                        getString(com.axend.lib_base.R.string.app_device_connecting)
                    mBinding.tvDeviceTips.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
                    mBinding.ivUsb.visibility = android.view.View.INVISIBLE
                    mBinding.ivRadar.setImageDrawable(null)
                    /*红外usb权限是否请求成功*/
                    initInfrared()
                }
                // USB设备移除
                UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                    val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                    // 处理设备移除的逻辑
                    mBinding.tvDeviceTips.text =
                        getString(com.axend.lib_base.R.string.app_device_connect_tips)
                    mBinding.tvDeviceTips.setCompoundDrawablesWithIntrinsicBounds(
                        com.axend.lib_base.R.mipmap.icon_weilianjie,
                        0,
                        0,
                        0
                    )
                    mBinding.ivUsb.visibility = android.view.View.VISIBLE
                    mBinding.ivRadar.setImageResource(com.axend.lib_base.R.mipmap.img_radar)

                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(usbBroadcastReceiver)
        SerialManage.getInstance().colse()
    }

    override fun connectMsg(path: String?, isSucc: Boolean) {
        if (isSucc){
            /*跳转*/
            Intent(this@UsbDeviceConnectActivity, MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(this)
            }
            finish()
        }
    }

    override fun readData(path: String?, bytes: ByteArray?, size: Int) {

    }

    override fun writeData(): RadarUpBean {
        return RadarUpBean(null, false)
    }

    override fun radarVersion(bytes: ByteArray?) {

    }

    override fun updata_button_click(): Boolean {
        return false
    }

    override fun progress(progress: Int, total: Int) {

    }

}

